package openapi

import (
	"strings"

	"github.com/getkin/kin-openapi/openapi3"
)

type ServerSelection struct {
	No        int                    `goblet:"no" json:"no,omitempty" yaml:"no,omitempty"`
	Url       string                 `goblet:"url" json:"url,omitempty" yaml:"url,omitempty"`
	Variables map[string]interface{} `goblet:"variables" json:"variables,omitempty" yaml:"variables,omitempty"`

	def *openapi3.Server
}

func (s *ServerSelection) AddDef(def *openapi3.Server) {
	s.def = def
}

func (s *ServerSelection) ToStatic() *openapi3.Server {
	if s.def == nil {
		return nil
	}
	if s.def.Variables == nil {
		return s.def
	}
	uri := s.def.URL
	for name, svar := range s.def.Variables {
		if s.Variables != nil {
			if v, ok := s.Variables[name]; ok {
				uri = strings.ReplaceAll(uri, "{"+name+"}", v.(string))
				continue
			}
		}
		uri = strings.ReplaceAll(uri, "{"+name+"}", svar.Default)
	}
	var static = &openapi3.Server{
		URL: uri,
	}
	return static
}
